package xyz.hubery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import xyz.hubery.domain.SysRolePrivilege;
import xyz.hubery.mapper.SysRolePrivilegeMapper;
import xyz.hubery.model.RolePrivilegesParam;
import xyz.hubery.service.SysRolePrivilegeService;

@Transactional
@Service
public class SysRolePrivilegeServiceImpl extends ServiceImpl<SysRolePrivilegeMapper, SysRolePrivilege> implements SysRolePrivilegeService{


    @Override
    public boolean addRolePrivileges(RolePrivilegesParam rolePrivilegesParam) {
        // 角色id
        Long roleId = rolePrivilegesParam.getRoleId();
        // 删除该角色原来的所有权限
        deleteAllPrivilegesByRoleId(roleId);
        // 授权新的权限

        List<Long> privilegeIds = rolePrivilegesParam.getPrivilegeIds();
        if(CollectionUtils.isEmpty(privilegeIds)){
            return true;
        }
        for (Long privilegeId : privilegeIds) {
            addRolePrivilege(roleId,privilegeId);
        }
        return false;
    }

    private void addRolePrivilege(Long roleId, Long privilegeId) {
        SysRolePrivilege rolePrivilege = new SysRolePrivilege();
        rolePrivilege.setRoleId(roleId);
        rolePrivilege.setPrivilegeId(privilegeId);
        this.save(rolePrivilege);
    }

    private void deleteAllPrivilegesByRoleId(Long roleId) {
         this.remove(new LambdaQueryWrapper<SysRolePrivilege>().eq(SysRolePrivilege::getRoleId, roleId));
    }
}
